<template>
  <div id="iqcEchart">
    <div id="echart">
      <div class="chart" ref="piechart" id="main" :style="{ width: '100%', height: '500px' }" v-show="chartData.lineData" v-loading="loading"></div>
    </div>
    <!-- 失控记录抽屉 -->
    <el-drawer v-model="showDrawer" show-close title="失控记录" :with-header="false" direction="rtl" size="55%" :modal="true" :modal-append-to-body="false" @close="clearDrawer">
      <div class="iqcOutControl">
        <QcOutControlRecChart ref="qcOutControlRecChartRef" />
      </div>
    </el-drawer>
  </div>
  <!-- <div class="chart" ref="piechart"></div> -->
</template>
<script lang="ts" setup>
import { Ref, ref, defineExpose, reactive, getCurrentInstance, onMounted } from 'vue';
import { ECharts, EChartsOption, init } from 'echarts';
import { formatDateTime, IsEmpty } from '@/utils/common';
import QcOutControlRecChart from './QcOutControlRecChart.vue'; //失控记录图表

defineExpose({
  getEchartData
});

// 变量定义区
let { proxy }: any = getCurrentInstance();
const chartType = ref('');
const chartHeight = ref('');
let chartData = reactive({
  xAxis: [],
  yAxis: [],
  yDisplayAxis: [],
  lineData: []
});
// let chart: ECharts;
const piechart: Ref<HTMLElement | null> = ref(null);
const resultForm = reactive({
  rptGroupId: null, //报告单元id
  rptGroupName: '',
  // selectWorkTeam: '', //选中的子工作组id
  insId: null, //仪器
  insName: '',
  insAnsId: null, //仪器项目
  itemDictId: null, //项目
  ansName: '',
  iqcMaterialIds: [],
  QCDateS: null, //开始时间
  QCDateE: null //结束时间
});
let showDrawer = ref(false);
let qcOutControlRecChartRef: any = ref(null);
let IQCResultId = ref('');

// 方法定义区 =====
onMounted(() => {});

// 查询数据
function getEchartData(val: any, iqcResultForm: any, chartHeight: any) {
  Object.assign(resultForm, iqcResultForm);
  if (iqcResultForm.iqcMaterialIds.length === 0) {
    chartData = { xAxis: [], yAxis: [], yDisplayAxis: [], lineData: [] };
    const myChart = init(piechart.value as HTMLElement);
    myChart.clear(); // 清除画布
    return;
  }
  const url = '/api/qc/chart/getResultChartData';
  let obj = {
    itemDictId: resultForm.itemDictId,
    QcMaterialIds: resultForm.iqcMaterialIds,
    QCDateS: resultForm.QCDateS,
    QCDateE: resultForm.QCDateE,
    val: val.value
  };
  proxy.$http
    .get(url, { params: obj })
    .then((res: any) => {
      if (res.data && Object.keys(res.data).length > 0) {
        chartData = res.data;
        initChart(val);
      } else {
        const myChart = init(piechart.value as HTMLElement);
        myChart.clear(); // 清除画布
        chartData = { xAxis: [], yAxis: [], yDisplayAxis: [], lineData: [] };
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
// 初始化图标
function initChart(val) {
  // 图表宽度自适应
  const chartBox = document.getElementById('echart');
  const chartDom = document.getElementById('main');
  //图表宽高计算
  chartssize(chartBox, chartDom);
  const myChart = init(piechart.value as HTMLElement);
  // 计算查询时间范围的天数
  const days = Math.ceil((new Date(resultForm.QCDateE).valueOf() - new Date(resultForm.QCDateS).valueOf()) / (24 * 3600 * 1000)) + 1;
  const xAxisData = setTimeX(days > 31 ? days : 31);
  const yAxisData = chartData.yAxis;
  const yDisplayAxisData = [];

  if (chartData.yDisplayAxis && chartData.yDisplayAxis.length > 0) {
    chartData.yDisplayAxis.forEach((item) => {
      yDisplayAxisData.push(parseFloat(parseFloat(item).toFixed(4)));
    });
  }
  const seriesData = [];
  if (chartData.lineData && chartData.lineData.length <= 0) {
    return;
  }
  chartData.lineData.forEach((item) => {
    const bestArr = [];
    bestArr.length = xAxisData.length;
    if (item.qcResults && item.qcResults.length > 0) {
      item.qcResults.forEach((data) => {
        if (data.isBestInDay) {
          // 最优结果放在一个数组中，形成一条折线图
          const index = xAxisData.findIndex((x) => {
            return data.qcDateStr === x;
          });
          if (index > -1) {
            bestArr[index] = {
              name: data.value,
              id: data.id,
              isOutControl: data.isOutControl,
              mean: data.mean,
              sd: data.sd,
              result: data.result,
              outControlRules: data.outControlRules,
              itemStyle: {
                color: data.isOutControl ? 'red' : item.lineColor
              } //单独给某个点设置颜色
            };
            // 如果为Z分数图，且结果大于最大Y轴值或小于最小Y轴值，在折线图中显示为最大值或最小值
            if (data.z > yAxisData[yAxisData.length - 1]) {
              bestArr[index].value = yAxisData[yAxisData.length - 1];
            } else if (data.z < yAxisData[0]) {
              bestArr[index].value = yAxisData[0];
            } else {
              bestArr[index].value = data.z;
            }
          }
        } else {
          // 非最优结果值单独放在一个数组中，作为单独的折线图【图中表现为，只有对应的点】
          const resData = [];
          const index = xAxisData.findIndex((x) => {
            return data.qcDateStr === x;
          });
          // 如果为Z分数图，且结果大于最大Y轴值或小于最小Y轴值，在折线图中显示为最大值或最小值
          if (index > -1) {
            resData.length = xAxisData.length;
            resData[index] = {
              name: data.value,
              id: data.id,
              isOutControl: data.isOutControl,
              mean: data.mean,
              sd: data.sd,
              result: data.result,
              outControlRules: data.outControlRules,
              itemStyle: {
                color: data.isOutControl ? 'red' : item.lineColor
              }
            };
            if (data.z > yAxisData[yAxisData.length - 1]) {
              resData[index].value = yAxisData[yAxisData.length - 1];
            } else if (data.z < yAxisData[0]) {
              resData[index].value = yAxisData[0];
            } else {
              resData[index].value = data.z;
            }
          }
          seriesData.push({
            name: item.materialName,
            type: 'line',
            data: resData,
            symbol: item.dictMark,
            symbolSize: 10,
            color: [item.dictLineColor]
          });
        }
      });
    }
    seriesData.push({
      name: item.materialName,
      type: 'line',
      data: bestArr,
      symbol: item.materialsId,
      symbolSize: 10,
      color: [item.dictLineColor],
      connectNulls: true //断点链接
    });
  });

  const option = {
    title: {
      // text: '2022-01-01至2022-05-01'
    },
    legend: {
      type: 'scroll',
      top: 10,
      itemWidth: 35,
      textStyle: {
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        // type: 'line',//指示器
      },
      confine: true, //是否将 tooltip 框限制在图表的区域内
      backgroundColor: 'rgba(255, 255, 255, 0.8)',
      borderRadius: 5,
      extraCssText: 'box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);',
      padding: [5, 10],
      textStyle: {
        color: '#333'
      },
      formatter: formatter
    },
    toolbox: {
      feature: {
        saveAsImage: { show: false }
      },
      right: 20
    },
    grid: {
      top: '50px',
      bottom: '70px',
      left: '70px',
      right: '50px'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      splitLine: {
        show: true
      },
      // splitNumber: 31,
      axisLabel: {
        interval: 0
      }, //强制显示所有坐标
      data: xAxisData
    },
    yAxis: {
      type: 'value',
      data: yAxisData,
      max: yAxisData[yAxisData.length - 1], //坐标轴刻度最大值
      min: yAxisData[0],
      splitNumber: yAxisData.length, //坐标轴的分割段数
      splitLine: {
        show: true,
        lineStyle: {
          // 坐标线
          color: ['#ccc', '#f56c6c', '#e6a23c', '#67c23a', '#333', '#67c23a', '#e6a23c', '#f56c6c']
        }
      },
      // Y轴坐标编辑
      axisLabel: {
        formatter(value, index) {
          if (val.value === 'LJ') {
            return yDisplayAxisData[index];
          } else {
            return value+'S';
          }
        }
      }
    },
    dataZoom: [
      {
        type: 'slider',
        start: 0,
        end: 100,
        height: 18,
        filterMode: 'empty',
        showDataShadow: false
      },
      {
        type: 'inside',
        start: 0,
        end: 100
      }
    ], //区域缩放
    series: seriesData
  };
  myChart.setOption(option, true); //第二个参数 true 用来清除上次数据
  // 折线图点击事件
  myChart.on('click', (params: any) => {
    // 控制台打印数据的名称
    if (params.data.isOutControl) {
      IQCResultId.value = params.data.id;
      IQCOutControl();
    }
  });
}

function chartssize(container, charts) {
  const w = getStyle(container, 'width').width;
  const h = getStyle(container, 'height').height;
  charts.style.width = w;
  return { width: w, height: h };
}
function setTimeX(num) {
  const arr = [] as any[];
  const QCDateS = new Date(formatDateTime(resultForm.QCDateS, 'yyyy-MM-dd')).valueOf();
  const QCDateE = new Date(formatDateTime(resultForm.QCDateE, 'yyyy-MM-dd')).valueOf();
  for (let index = 0; index < num; index++) {
    if (QCDateS + 24 * 60 * 60 * 1000 * index <= QCDateE) {
      arr.push(formatDateTime(new Date(QCDateS + 24 * 60 * 60 * 1000 * index), 'MM.dd'));
    } else {
      arr.push('');
    }
  }
  return arr;
}
function getStyle(el, name) {
  if (window.getComputedStyle) {
    return window.getComputedStyle(el, null);
  } else {
    return el.currentStyle;
  }
}
function formatter(params, ticket, callback) {
  let str = params[0].axisValueLabel + '<br />';
  for (let i = params.length - 1; i >= 0; i--) {
    if (!IsEmpty(params[i].data)) {
      const outControlRules = params[i].data.outControlRules;
      str += '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:' + params[i].color + ';"></span>测试值：';
      str += '<span style="font-weight:bold;display: inline-block;width: 60px;margin-right:8px;">' + params[i].data.result + '</span>';
      str += '靶值：<span style="display: inline-block;width: 40px;margin-right:8px;">' + params[i].data.mean + '</span>';
      str += 'sd值：<span style="display: inline-block;width: 40px;margin-right:10px;">' + params[i].data.sd + '</span>';
      if (!IsEmpty(outControlRules)) {
        str += '失控规则：<span style="display: inline-block;color:red;">' + outControlRules + '</span>';
      }
      str += '<br />';
    }
  }
  return str;
}

// 点击右键菜单里的失控处理
function IQCOutControl() {
  showDrawer.value = true;
  proxy.$nextTick(() => {
    qcOutControlRecChartRef.value.initPage(IQCResultId);
  });
}
function clearDrawer() {
  showDrawer.value = false;
}
</script>

<style scoped>
.chart {
  width: 100%;
  height: 400px;
}
</style>
